import sys
import os
import os.path
import shutil
import logging
import tempfile
import zipfile

from nose.tools import assert_equals
from subprocess import Popen, PIPE

def joinpaths(p, *paths):
    return os.path.abspath(os.path.join(p, *paths))

def unzip(filename, destdir):
    """
    Unzips target zip file into destination directory.
    Returns directory into which archive was unzipped.
    """
    zf = zipfile.ZipFile(filename)
    if not os.path.isdir(destdir):
        os.mkdir(destdir, 0755)
    #logging.debug("Created: %s" % destdir)
    
    names = zf.namelist()
    for name in names:
        targetname = os.path.join(destdir, name)
        #logging.debug("Unzipping %s" % targetname)
        if name.endswith(os.path.sep):
            os.mkdir(targetname)
        else:
            fout = open(targetname, 'wb') # We assume file CAN be binary
            fout.write(zf.read(name))
            fout.close()

    return destdir, names

def unzip_to_tmpdir(filename):
    """
    Mostly like unzip but it first creates
    temporal directory.
    """
    #logging.debug("Creating temp directory...")
    tmpdir = tempfile.mkdtemp()
    #logging.debug("Created %s" % tmpdir)
    #logging.debug("Will now unzip %s into %s" % (filename, tmpdir))

    return unzip(filename, tmpdir)

def do_cmd(command, args='', assert_status=0):
    """
    Returns output of the shell command.
    """
    cmd = ' '.join(filter(None, (command, args)))
    p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True, close_fds=True)
    stdout, stderr = p.communicate()
    if isinstance(assert_status, int):
        # Assert the status code
        assert_equals(p.returncode, assert_status, "'%s' returned not "
            "%d status code (it returned %d)"
            % (cmd, assert_status, p.returncode))
    return stdout

